/****************************************************************************
 * 2025.8 楠
 ****************************************************************************/

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using ProjectSurvivor;
using System.Linq;

namespace QFrameworkSurvivor
{
	public partial class CoinUpgradePanel : UIElement,IController
	{
        private void Awake()
		{
            CoinUpgradeltemTemplate.Hide();

            Global.Coin.RegisterWithInitValue(coin =>
            {

                CoinText.text = "金币:" + coin;

            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            foreach (var coinUpgradeitem in this.GetSystem<CoinUpgradeSystem>().Items.Where(item => !item.UpgradeFinish))
            {
                CoinUpgradeltemTemplate.InstantiateWithParent(CoinUpgradeltemRoot)
                    .Self(self =>
                    {
                        var item = coinUpgradeitem;
                        self.GetComponentInChildren<Text>().text = item.Description + " " + item.Price + "金币";
                        self.onClick.AddListener(() =>
                        {
                            AudioKit.PlaySound("BtnClick");
                            item.Upgrade();
                        });
                        var selfCache = self;

                        item.OnChanged.Register(() => 
                        {
                            if(item.ConditionCheck())
                            {
                                selfCache.Show();
                            }
                            else
                            {
                                selfCache.Hide();
                            }
                        }).UnRegisterWhenGameObjectDestroyed(selfCache);

                        if (item.ConditionCheck())
                        {
                            selfCache.Show();
                        }
                        else
                        {
                            selfCache.Hide();
                        }

                        Global.Coin.RegisterWithInitValue(coin =>
                        {
                            if (coin >= item.Price)
                            {
                                selfCache.interactable = true;
                            }
                            else
                            {
                                selfCache.interactable = false;
                            }

                        }).UnRegisterWhenGameObjectDestroyed(self);
                    });
            }

            BtnClose.onClick.AddListener(() =>
            {
                AudioKit.PlaySound("BtnClick");
                this.Hide();
            });
        }

		protected override void OnBeforeDestroy()
		{
		}

        public IArchitecture GetArchitecture()
        {
            return Global.Interface;
        }
    }
}